import request from 'request'
import fs from 'fs'
import os from 'os'
import path from 'path'
import crypto from 'crypto'

export function downloadFromUrl (url: string) {
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  // link.setAttribute('download')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link) // 下载完成移除元素
}

export function downloadFromBlob (data: Blob, name?: string) {
  const url = window.URL.createObjectURL(new Blob([data]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  if (name) link.setAttribute('download', name)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link) // 下载完成移除元素
  window.URL.revokeObjectURL(url) // 释放掉blob对象
}

export function downloadTo (url: string, path: string, sha = false): Promise<{ path: string; sha?: string }> {
  return new Promise((resolve, reject) => {
    const stream = fs.createWriteStream(path)
    let md5sum: any
    if (sha) {
      md5sum = crypto.createHash('md5')
      stream.on('pipe', function (s) {
        s.on('data', chunk => {
          md5sum.update(chunk)
        })
      })
    }
    stream.addListener('finish', () => {
      let c
      if (md5sum) c = md5sum.digest('hex').toUpperCase()
      resolve({ path, sha: c })
    })
    stream.addListener('error', err => reject(err))
    request(url, { strictSSL: false }).pipe(stream)
  })
}

export function genTmpPath (name: string) {
  const uid = Date.now() + String(Math.random()).slice(-6)
  const p = path.resolve(os.tmpdir(), uid + '-' + normolizeName(name))
  console.log('缓存地址: ' + p)
  return path.resolve(p)

  // 替换特殊字符
  function normolizeName (name = '') {
    return name.replace(/["“”]/g, '-')
  }
}
